﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Windows.Interactivity;

namespace nRoute.Samples.SquareAway.Behaviors
{
    public class SetContainerPositionBehavior 
        : Behavior<FrameworkElement>
    {
        private const double AVAILABLE_WIDTH = 67d;
        private const double AVAILABLE_HEIGHT = 66d;

        public static readonly DependencyProperty RowProperty =
            DependencyProperty.Register("Row", typeof(int), typeof(SetContainerPositionBehavior),
            new PropertyMetadata(0, OnRowChanged));

        public static readonly DependencyProperty ColumnProperty =
            DependencyProperty.Register("Column", typeof(int), typeof(SetContainerPositionBehavior),
            new PropertyMetadata(0, OnColumnChanged));

        private FrameworkElement _container;

#region Properties

        public int Row
        {
            get { return Convert.ToInt32(GetValue(RowProperty)); }
            set { SetValue(RowProperty, value); }
        }

        public int Column
        {
            get { return Convert.ToInt32(GetValue(ColumnProperty)); }
            set { SetValue(ColumnProperty, value); }
        }

#endregion

#region Handlers

        private static void OnColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((SetContainerPositionBehavior)d).UpdateCanvasPosition();
        }

        private static void OnRowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((SetContainerPositionBehavior)d).UpdateCanvasPosition();
        }

#endregion

#region Helpers

        private void UpdateCanvasPosition()
        {
            if (this.AssociatedObject == null) return;
            if (Column == -1 || Row == -1) return;

            if (_container == null)
            {
                var _itemsControl = ItemsControl.ItemsControlFromItemContainer(VisualTreeHelper.GetParent(this.AssociatedObject));
                _container = (FrameworkElement)_itemsControl.ItemContainerGenerator.ContainerFromItem(this.AssociatedObject.DataContext);
                _container.Margin = new Thickness();
            }

            // update margins - we use this
            var _margin = _container.Margin;
            _margin.Left = Column * AVAILABLE_WIDTH;
            _margin.Top = Row * AVAILABLE_HEIGHT;
            _container.Margin = _margin;
        }

#endregion

    }
}